
package xj.lang;

public class JavaLangUtil { 

  /**
   * return the position in the line with the first matching quoteChar after begin.
   *
   * given the begin position of quoted constant, find the end 
   * using a state diagram 
   */
  public static int endOfQuote(String line, char quoteChar, int begin) {
    if (line != null) { 
      int state = INIT_STATE;
      int count = 0;
      int len = line.length();
      char c;
      int i;
      for (i = begin; i < len; i++) {
	c = line.charAt(i);
	switch (state) {
        case INIT_STATE:
	  if (c == quoteChar) {
	    return i + 1;
	  }
	  if (c == '\\') {
	    state = SLASH_STATE;
	  }
	  break;

        case SLASH_STATE:
	  if (c == 'u' || c == 'U') {
	    state = UNICODE_STATE;
	  } else if (c >= '0' && c <= '7') {
	    state = OCT_STATE;
	    count = 1;
	  } else {
	    state = INIT_STATE;
	  }
	  break;

        case UNICODE_STATE:
	  if (c >= '0' && c <= '9' ||
	      c >= 'a' && c <= 'f' ||
	      c >= 'A' && c <= 'F') {
	    state = HEX_STATE;
	    count = 1;
	  } else {
	    state = INIT_STATE;
	  }
	  break;

        case OCT_STATE:
	  if (c < '0' ||
	      c > '7' ||
	      ++count >= 3) {
	    state = INIT_STATE;
	  }
	  break;

        case HEX_STATE:
	  if (!(c >= '0' && c <= '9' ||
		c >= 'a' && c <= 'f' ||
		c >= 'A' && c <= 'F') ||
	      ++count >= 4) {
	    state = INIT_STATE;
	  }
	  break;
	}
      }
    }
    return -1;
  }

  public static boolean isIdentifier(String s) {
    if (s != null && 
	Character.isJavaIdentifierStart(s.charAt(0))) {
      for (int i = 1; i < s.length(); i++) {
        if (!Character.isJavaIdentifierPart(s.charAt(i))) {
          return false;
        }
      }
      return true;
    }
    return false;
  }

  public static boolean isClassName(String s) {
    if (s != null) { 
      char ch = s.charAt(0);
      if (Character.isJavaIdentifierStart(ch) &&
	  Character.isUpperCase(ch)) {
	for (int i = 1; i < s.length(); i++) {
	  if (!Character.isJavaIdentifierPart(s.charAt(i))) {
	    return false;
	  }
	}
	return true;
      }
    }
    return false;
  }

  public static boolean isNumber(String s) {
    if (s != null) { 
      int len = s.length();
      char c;
      for (int i = 0; i < len; i++) {
	c = s.charAt(i);
	if (!Character.isDigit(c) &&
	    c != '.' &&
	    c != 'd' &&
	    c != 'D' &&
	    c != 'e' &&
	    c != 'E' &&
	    c != 'f' &&
	    c != 'F' &&
	    c != 'l' &&
	    c != 'L') {
	  return false;
	}
      }
      if (len == 1) {
	c = s.charAt(0);
	if (c == '.' ||
	    c == 'd' ||
	    c == 'D' ||
	    c == 'e' ||
	    c == 'E' ||
	    c == 'f' ||
	    c == 'F' ||
	    c == 'l' ||
	    c == 'L') {
	  return false;
	}
      }
    }
    return true;
  }

  protected static final int INIT_STATE = 0;
  protected static final int SLASH_STATE = 1;
  protected static final int UNICODE_STATE = 2;
  protected static final int OCT_STATE = 3;
  protected static final int HEX_STATE = 4;

}
